// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

import {
	LOGIN_STATUS,
	UID,
	USER_INFO
} from '../../config/cache.js';
import Cache from '../../utils/cache.js';

const state = {
	token: Cache.get(LOGIN_STATUS) || false,
	backgroundColor: "#fff",
	userInfo: {},
	uid: Cache.get(UID) || 0,
	homeActive: false,
	phoneStatus: true,
	pageFooter: wx.getStorageSync('pageFoot') || {},
	activityTab: ''
};

const mutations = {
	SETPHONESTATUS(state, val) {
		state.phoneStatus = val;
	},
	LOGIN(state, opt) {
		state.token = opt.token;
		Cache.set(LOGIN_STATUS, opt.token, opt.time);
	},
	SETUID(state, val) {
		state.uid = val;
		Cache.set(UID, val);
	},
	UPDATE_LOGIN(state, token) {
		state.token = token;
	},
	ACTIVITYTAB(state, tab) {
		state.activityTab = tab;
	},
	LOGOUT(state) {
		state.token = false;
		state.uid = 0
		Cache.clear(LOGIN_STATUS);
		Cache.clear(USER_INFO);
		Cache.clear(UID);
		Cache.clear('snsapiCode');
	},
	BACKGROUND_COLOR(state, color) {
		state.backgroundColor = color;
		// 小程序中不需要设置document.body.style.backgroundColor
	},
	UPDATE_USERINFO(state, userInfo) {
		state.userInfo = userInfo;
		Cache.set(USER_INFO, userInfo);
	},
	OPEN_HOME(state) {
		state.homeActive = true;
	},
	CLOSE_HOME(state) {
		state.homeActive = false;
	},
	FOOT_UPLOAD(state, data) {
		state.pageFooter = data
	}
};

const actions = {
	/**
	 * 获取用户信息
	 * 使用 userManager 避免循环依赖
	 * @param {Object} context - Vuex context
	 * @param {Boolean} force - 是否强制刷新
	 */
	async USERINFO({ state, commit }, force) {
		// 如果不强制刷新且已有数据，直接返回
		if (state.userInfo && Object.keys(state.userInfo).length > 0 && !force) {
			return Promise.resolve(state.userInfo);
		}
		
		try {
			// 动态导入 userManager 避免循环依赖
			const userManager = (await import('../../utils/userManager.js')).default;
			
			// 使用 userManager 获取用户信息
			const userInfo = await userManager.getUserInfo(force, false);
			
			if (userInfo) {
				// userManager 内部已经调用了 commit，这里无需重复
				return userInfo;
			} else {
				return null;
			}
		} catch (error) {
			console.error('获取用户信息失败:', error);
			return null;
		}
	}
};

export default {
	state,
	mutations,
	actions
};
